package com.ysxsoft.wdg.ui.fragment.order;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.classic.common.MultipleStatusView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.order.PinOrderDetailActivity;
import com.ysxsoft.wdg.base.BaseFragment;
import com.ysxsoft.wdg.bean.response.CollectShopResponse;
import com.ysxsoft.wdg.bean.response.PinOrderResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.ui.activity.KanWebViewActivity;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ListObserverMap;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;

public class PinOrderFragment extends BaseFragment implements OnRefreshListener, OnLoadmoreListener, ListObserverMap.IListDataChangeObserver {
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;
    private String uid;
    private int pinType=0;
    private int page = 1;
    private CustomAdapter adapter;
    private long systemTime;
    private HashMap<String, CountTimer> timerMap = new HashMap<>();
    private int clickPosition;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_pin_order;
    }

    @Override
    protected void initData() {
        uid = SharePrefUtils.getUserId();
        pinType = getArguments().getInt("type", 1);//0全部 1代付款2拼团中3拼团成功4拼团失败
        if (pinType == 0) {
            pinType = 5;
        }
        ListObserverMap.reg("PinOrderFragment", this);
        initAdapter();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ListObserverMap.remove("PinOrderFragment");
    }

    private void initAdapter() {
        adapter = new CustomAdapter(R.layout.item_pin_order);
        recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerview.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                PinOrderResponse.DataBean dataBean = (PinOrderResponse.DataBean) adapter.getItem(position);
                if (dataBean.getIstuan() == 3) {//拼团失败
                    return;
                }
//                Intent intent = new Intent(getActivity(), PinOrderDetailActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putSerializable("data", dataBean);
//                intent.putExtras(bundle);
//                startActivity(intent);
                Intent intent = new Intent(getActivity(), PinOrderDetailActivity.class);
                intent.putExtra("orderid", dataBean.getOrderid() + "");
                startActivity(intent);
            }
        });
        getList();
    }

    @Override
    protected void setListener() {
        refreshLayout.setOnLoadmoreListener(this);
        refreshLayout.setOnRefreshListener(this);
    }

    private boolean isFirst = true;

    private void getList() {
        if (isFirst) {
            multStatusView.showLoading();
            isFirst = false;
        }
        OkHttpUtils.post()
                .url(UrlHost.PIN_ORDER)
//                .addParams("uid", uid)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("page", page + "")
                .addParams("type", pinType + "")
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (!call.isCanceled()) {
                            multStatusView.showError();
                            reset();
                        }
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        reset();
                        try {
                            if (response != null) {
                                multStatusView.showContent();
                                PinOrderResponse pinOrderResponse = JsonUtils.parseByGson(response, PinOrderResponse.class);
                                if (pinOrderResponse == null) {
                                    return;
                                }
                                if (CallbackCode.SUCCESS.equals(pinOrderResponse.getCode())) {
                                    List<PinOrderResponse.DataBean> list = pinOrderResponse.getData();
                                    if (page == 1) {
                                        if (list.size() == 0) {
                                            multStatusView.showEmpty();
                                        }
                                        systemTime = SystemClock.elapsedRealtime();
                                        adapter.setNewData(list);
                                    } else {
                                        adapter.addData(list);
                                    }
                                } else {
                                    if (page == 1) {
                                        multStatusView.showEmpty();
                                        adapter.setNewData(new ArrayList<>());
                                    }
                                }
                            } else {
                                multStatusView.showError();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private boolean isSystemTimeFirst = true;//是否是第一次记录时间

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        page++;
        getList();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        page = 1;
        getList();
    }

    private void reset() {
        try {
            if (refreshLayout.isRefreshing()) {
                refreshLayout.finishRefresh(true);
            }
            refreshLayout.finishLoadmore();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void ping() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                page = 1;
//                getList();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        page=1;
        getList();
    }

    @Override
    public void pay() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                page = 1;
//                getList();
            }
        });
    }

    @Override
    public void cancel() {
        //取消订单
        Log.e("tag", "cancel");
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                page = 1;
                pinType = getArguments().getInt("type", 1);
                getList();
            }
        });
    }

    private class CustomAdapter extends BaseQuickAdapter<PinOrderResponse.DataBean, BaseViewHolder> {
        public CustomAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        public void onViewRecycled(@NonNull BaseViewHolder holder) {
            super.onViewRecycled(holder);
            View view = holder.getView(R.id.countDownTime);//移除countDownTime
            if (view != null && view.getVisibility() == View.VISIBLE && view.getTag() != null) {
                CountTimer timer = (CountTimer) view.getTag();
                timer.cancel();
            }
        }

        @Override
        protected void convert(BaseViewHolder helper, PinOrderResponse.DataBean item) {
            RecyclerView recyclerView = helper.getView(R.id.recyclerview);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            CustomChildAdapter adapter = new CustomChildAdapter(R.layout.item_order_inner);
            recyclerView.setAdapter(adapter);
            adapter.setNewData(item.getDetail());
            recyclerView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    View view = helper.getConvertView();
                    return view.onTouchEvent(event);
                }
            });

            helper.setText(R.id.people, "拼团中,还差" + item.getCa_num() + "人成团");
            helper.setText(R.id.tv_num_all, "共" + item.getTotal_num() + "件商品 实付￥" + item.getAccount());
            helper.setText(R.id.tv_no, "订单号：" + item.getDsn());
            TextView tv_l = helper.getView(R.id.tv_l);//左按钮
            TextView tv_r = helper.getView(R.id.tv_r);//右按钮
            int type = 0;
            if (item.getStatus() == 0) {//0未支付1支付成功
                type = -1;
            } else {//支付成功
                if (item.getIstuan() == 0) {//0拼团中1拼团成功2拼团失败
                    type = 1;
                } else if (item.getIstuan() == 1) {
                    type = 2;
                } else if (item.getIstuan() == 2) {
                    type = 3;
                }
            }
            boolean hideCountDownTime = false;
            boolean hideLeft = false;//拼团失败隐藏右按钮
            switch (type) {
                case -1:
                    hideLeft = false;
                    hideCountDownTime = true;
                    helper.setText(R.id.tv_status, "待付款");
                    tv_l.setText("取消订单");
                    tv_r.setText("立即支付");

                    tv_l.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            clickPosition = helper.getAdapterPosition();
                            cancelOrder(item.getOrderid() + "");
                        }
                    });
                    tv_r.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //跳转详情支付
                            Intent intent = new Intent(getActivity(), PinOrderDetailActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("orderid", item.getOrderid() + "");
                            bundle.putSerializable("data", item);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                    });
                    break;
                case 1://拼团中
                    hideLeft = false;
                    hideCountDownTime = false;
                    helper.setText(R.id.tv_status, "");
                    tv_l.setText("拼团详情");
                    tv_r.setText("邀请参团");

                    TextView countDownTime = helper.getView(R.id.countDownTime);
                    String key = item.getOrderid() + "";
                    long t = SystemClock.elapsedRealtime() - systemTime;
                    long mss = item.getCa_time() * 1000;//时间
                    mss -= t;//总时间减去  已运行的时间
                    int interval = 1000;
                    CountTimer timer = new CountTimer(mss, interval);
                    timer.setTextView(countDownTime);
                    timerMap.put(key, timer);
                    timer.start();
                    helper.setTag(R.id.countDownTime, timer);

                    tv_l.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            KanWebViewActivity.start(getActivity(), UrlHost.BASE_URL+"/index.html#/groupDetails?detailId=" + item.getTuanid()+"&orderId="+item.getOrderid());
                        }
                    });
                    break;
                case 2://拼团成功
                    hideLeft = false;
                    hideCountDownTime = true;
                    helper.setText(R.id.tv_status, "拼团成功");
                    tv_l.setText("拼团详情");
                    tv_r.setText("订单详情");

                    tv_l.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            KanWebViewActivity.start(getActivity(), UrlHost.BASE_URL+"/index.html#/groupDetails?detailId=" + item.getTuanid()+"&orderId="+item.getOrderid());
                        }
                    });
                    break;
                case 3://拼团失败
                    hideLeft = true;
                    hideCountDownTime = true;
                    helper.setText(R.id.tv_status, "拼团失败");
                    tv_l.setText("拼团详情");

                    tv_l.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            KanWebViewActivity.start(getActivity(), UrlHost.BASE_URL+"/index.html#/groupDetails?detailId=" + item.getTuanid()+"&orderId="+item.getOrderid());
                        }
                    });
                    break;
            }
            //是否显示倒计时时间
            LinearLayout top = helper.getView(R.id.top);
            if (hideCountDownTime) {
                top.setVisibility(View.GONE);
            } else {
                top.setVisibility(View.VISIBLE);
            }

            //拼团失败
            if (hideLeft) {
                tv_r.setVisibility(View.GONE);
            } else {
                tv_r.setVisibility(View.VISIBLE);
            }

            if (type == -1) {//待付款 显示灰色背景
                tv_l.setTextColor(getResources().getColor(R.color.black6));
                tv_l.setBackgroundResource(R.drawable.bg_gray_sy_x);
            } else {//其他状态时  左侧按钮显示边框
                tv_l.setTextColor(getResources().getColor(R.color.colorPrimary));
                tv_l.setBackgroundResource(R.drawable.bg_rect_red_storke);
            }
        }
    }

    /**
     * 商品
     */
    private class CustomChildAdapter extends BaseQuickAdapter<PinOrderResponse.DataBean.DetailBean, BaseViewHolder> {
        public CustomChildAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(BaseViewHolder helper, PinOrderResponse.DataBean.DetailBean item) {
            ImageView iv_pic = helper.getView(R.id.iv_pic);
            ImageView icon = helper.getView(R.id.icon);
            Glide.with(getActivity()).load(item.getPic()).into(iv_pic);
            icon.setFocusable(false);
            iv_pic.setFocusable(false);
            helper.setText(R.id.tv_name, item.getName());
            helper.setText(R.id.tv_money, item.getL_price());
            helper.setText(R.id.tv_old_money, item.getPrice());
            helper.setText(R.id.tv_num, "x" + item.getNum());
            TextView oldMoney = helper.getView(R.id.tv_old_money);
            oldMoney.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        }
    }

    private class CountTimer extends CountDownTimer {
        private TextView textView;

        public CountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        public void setTextView(TextView textView) {
            this.textView = textView;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            textView.setText(ssToStr(millisUntilFinished));
        }

        @Override
        public void onFinish() {
            textView.setText("拼团结束!");
        }
    }

    private String ssToStr(long s) {
        s = s / 1000;
        long h = s / 3600;
        long m = (s - h * 3600) / 60;
        long ss = s % 60;
        long d = h / 24;
        String str = "";
        if (d > 0) {
            str = String.format("剩余%02d天%02d小时%02d分%02d秒", d, h % 24, m, ss);
        } else {
            str = String.format("剩余%02d小时%02d分%02d秒", h % 24, m, ss);
        }
        return str;
    }

    /**
     * 取消订单
     */
    private void cancelOrder(String orderId) {
        OkHttpUtils.post()
                .url(UrlHost.CANCEL_TUAN_ORDER)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    CollectShopResponse collectShopResponse = JsonUtils.parseByGson(response, CollectShopResponse.class);
                    if (collectShopResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(collectShopResponse.getCode())) {
                        ToastUtils.showToast(collectShopResponse.getMs());
                        page = 1;
                        getList();
                    } else {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

}
